package com.runa.persistence.service;

import com.runa.persistence.CollectionUtil;
import com.runa.persistence.entity.EntityEquipMap;
import com.runa.persistence.repository.EquipMapRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 2024/7/16 11:22
 * zhangYB
 */
@Slf4j
//@Service
public class EquipMapService {


//    @Resource
    private EquipMapRepository equipMapRepository;

    public void saveGdReadResponse(String netSerial, Integer equIndex, List<String> equSerials, String requestMessage, String responseMessage) {
        try {
            if (null == equSerials || equSerials.isEmpty()) {
                saveGdReadResponse(netSerial, null, requestMessage, responseMessage, equIndex, "光大");
            } else {
                Integer index = equIndex;
                for (String equSerial : equSerials) {
                    saveGdReadResponse(netSerial, equSerial, requestMessage, responseMessage, index++, "光大");
                }
            }
        } catch (Exception e) {
            log.error("光大: ", e);
        }
    }

    public void saveGdReadResponse(String netSerial, String serial, String requestMessage, String responseMessage, Integer equIndex, String type) {
        Map<Integer, EntityEquipMap> indexMap = equipMapRepository.findByNetSerial(netSerial).stream().collect(Collectors.toMap(EntityEquipMap::getEquIndex, Function.identity()));
        EntityEquipMap entityEquipMap = indexMap.get(equIndex);
        if (null != entityEquipMap) {
            save(entityEquipMap.getId(), netSerial, serial, requestMessage, responseMessage, equIndex, type);
        } else {
            save(null, netSerial, serial, requestMessage, responseMessage, equIndex, type);
        }
    }

    public void save(Integer id, String netSerial, String serial, String requestMessage, String responseMessage, Integer equIndex, String type) {
        EntityEquipMap entityEquipMap = new EntityEquipMap();
        entityEquipMap.setId(id);
        entityEquipMap.setNetSerial(netSerial);
        entityEquipMap.setSerial(serial);
        entityEquipMap.setRequestMessage(requestMessage);
        entityEquipMap.setResponseMessage(responseMessage);
        entityEquipMap.setEquIndex(equIndex);
        entityEquipMap.setType(type);
//        equipMapRepository.save(entityEquipMap);
    }

    public EntityEquipMap getEquipMap(String netSerial, String serial) {
        List<EntityEquipMap> equipMapList = equipMapRepository.findByNetSerialAndSerial(netSerial, serial);
        if (CollectionUtil.isNotEmpty(equipMapList)) {
            return equipMapList.get(0);
        }
        return null;
    }


}
